import 'package:flutter/widgets.dart';

///自定义更新配置
typedef CustomUpdateShouldNotify = bool Function(Widget oldWidget);

///封装InheritedWidget
class VgInheritedWidget<T> extends StatefulWidget {

  final Widget child;

  ///数据
  final T initData;

  ///更新条件
  final CustomUpdateShouldNotify customUpdateShouldNotify;
  
  ///网络请求回调
  final VoidCallback refreshHttpCallback;

  VgInheritedWidget({Key key,@required this.initData, @required this.child, this.customUpdateShouldNotify, this.refreshHttpCallback}) : super(key: key);

  ///获取组件
  static _CustomInheritedWidget<T> of<T>(BuildContext context,{bool listen = true}){
    if(listen){
      return context?.dependOnInheritedWidgetOfExactType<_CustomInheritedWidget<T>>();
    }
    return (context?.getElementForInheritedWidgetOfExactType<_CustomInheritedWidget<T>>()?.widget as _CustomInheritedWidget);
  }

  ///更新数据
  static void updateData<T>(BuildContext context,T newData) {
    of<T>(context, listen: false)?.state?.updateData(newData);
  }

  ///获取数据
  static T getData<T>(BuildContext context,{bool listen = true}){
    return of<T>(context,listen: listen)?.data;
  }

  ///网络请求更新
  static void refreshHttp<T>(BuildContext context){
    _VgInheritedWidgetState<T> state =  of<T>(context, listen: false)?.state;
    if(state?.widget?.refreshHttpCallback == null){
      return;
    }
    state?.widget?.refreshHttpCallback();
  }

  @override
  _VgInheritedWidgetState<T> createState() => _VgInheritedWidgetState();
}

class _VgInheritedWidgetState<T> extends State<VgInheritedWidget> {

  T data;

  @override
  void initState() {
    super.initState();
    data = widget?.initData;
  }

  updateData(T newData){
    setState(() {
      data = newData;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _CustomInheritedWidget<T>(
      data: data,
      child: widget?.child,
      state: this,
      customUpdateShouldNotify: widget?.customUpdateShouldNotify,
    );
  }
}

///自定义InheritedWidget
class _CustomInheritedWidget<T> extends InheritedWidget{

  ///数据
  final T data;

  final CustomUpdateShouldNotify customUpdateShouldNotify;

  ///获取上层数据更新引用
  final _VgInheritedWidgetState state;

  const _CustomInheritedWidget({this.data,@required Widget child,@required this.state,this.customUpdateShouldNotify, }):super(child:child);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => customUpdateShouldNotify ?? true;



}